package com.travel.server.manager.impl.sal;

import com.travel.server.manager.impl.vo.MenuVo;
import com.travel.server.manager.model.MenuInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/20 15:58
 * @Desc:
 */
public class MenuSal {

    public static List<MenuVo> makeMenu(List<MenuInfo> list){
        List<MenuVo> firstList = getFirstMenu(list);
        for(MenuVo menuVo : firstList){
            menuVo.setChildList(getChild(menuVo.getMenuCode(), list));
        }
        return firstList;
    }

    private static List<MenuVo> getFirstMenu(List<MenuInfo> list){
        List<MenuVo> firstList = new ArrayList<>();
        for(MenuInfo menuInfo : list){
            if(menuInfo.getParentCode() == null){
                firstList.add(makeVo(menuInfo));
            }
        }
        return firstList;
    }

    private static List<MenuVo> getChild(Integer parentCode, List<MenuInfo> list) {
        // 子菜单
        List<MenuVo> childList = new ArrayList<>();
        for (MenuInfo menu : list) {
            if (parentCode.equals(menu.getParentCode())) {
                childList.add(makeVo(menu));
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (MenuVo menu : childList) {
            menu.setChildList(getChild(menu.getMenuCode(), list));
        }
        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

    private static MenuVo makeVo(MenuInfo menuInfo){
        MenuVo vo = new MenuVo();
        vo.setMenuCode(menuInfo.getMenuCode());
        vo.setMenuId(menuInfo.getId());
        vo.setMenuName(menuInfo.getName());
        vo.setParentCode(menuInfo.getParentCode());
        vo.setMenuType(menuInfo.getMenuType());
        return vo;
    }
}
